<template>
  <view class="history-container">
    <!-- 顶部标题栏 -->
    <view class="history-header">
      <text class="title">浏览历史</text>
      <text class="clear-btn" @click="clearHistory" v-if="historyList.length > 0">清空</text>
    </view>

    <!-- 历史记录列表 -->
    <scroll-view class="history-list" scroll-y>
      <view 
        class="history-item" 
        v-for="(item, index) in historyList" 
        :key="index"
        @click="goToDetail(item.bookId)"
      >
        <image class="book-cover" :src="item.cover || '/static/屏幕截图 2025-06-22 200009.png'" mode="aspectFill" />
        <view class="book-info">
          <text class="book-name">{{ item.bookName }}</text>
          <text class="book-author">{{ item.author }}</text>
          <!-- 书籍评分 -->
          <text class="book-score" v-if="item.score">评分：{{ item.score }}</text>
          <!-- 书籍类型展示 -->
          <view class="book-types" v-if="item.types && item.types.length">
            <text class="type-tag" v-for="(type, i) in item.types" :key="i">
              {{ type }}
            </text>
          </view>
          <!-- 出版社信息 -->
          <text class="book-publisher" v-if="item.publisher">{{ item.publisher }}</text>
          <text class="view-time">浏览时间：{{ formatTime(item.viewTime) }}</text>
        </view>
        <uni-icons type="forward" size="20" color="#999"></uni-icons>
      </view>

      <!-- 空状态 -->
      <view class="empty-tip" v-if="historyList.length === 0 && !loading">
        <image src="/static/images/no-history.png" mode="aspectFit" />
        <text>暂无浏览历史</text>
      </view>

      <!-- 加载状态 -->
      <view v-if="loading" class="loading-tip">
        <text>加载中...</text>
      </view>
    </scroll-view>
  </view>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { onShow } from '@dcloudio/uni-app'

const historyList = ref([])
const loading = ref(false)
const BASE_URL = 'http://192.168.153.1:8080' // 后端API基础地址

onShow(() => {
  loadHistory()
})

// 加载浏览历史
const loadHistory = async () => {
  const user = uni.getStorageSync('userInfo')
  if (!user?.U_Id) {
    uni.showToast({
      title: '请先登录',
      icon: 'none'
    })
    return
  }
  
  console.log('用户ID:', user.U_Id)
  loading.value = true
  
  try {
    const [err, res] = await new Promise((resolve) => {
      uni.request({
        url: `${BASE_URL}/history/seekByUserId`,
        method: 'POST',
        data: { 
          userId: user.U_Id 
        },
        header: {
          'Content-Type': 'application/json'
        },
        success: (res) => resolve([null, res]),
        fail: (err) => resolve([err, null])
      })
    })
    
    if (err) throw err
    
    console.log('API响应:', res)
    
    if (res.statusCode === 200) {
      if (res.data.code === 200200) {
        // 正确处理API响应数据结构
        const booksData = res.data.data?.books || []
        console.log('原始书籍数据:', booksData)
        
        // 映射API字段到模板期望的字段
        historyList.value = booksData.map((book, index) => ({
          bookId: book.book_id,
          bookName: book.book_name,
          author: book.author,
          score: book.score,
          bookType: book.book_type,
          publisher: book.publisher,
          isbn: book.isbn,
          introduction: book.introduction,
          cover: book.cover_url || '', // 如果API有封面字段
          types: [book.book_type], // 将书籍类型作为types数组
          viewTime: new Date().toISOString() // 由于API没有浏览时间
        }))
        
        // 去重处理（根据bookId去重）
        const uniqueBooks = []
        const seenIds = new Set()
        historyList.value.forEach(book => {
          if (!seenIds.has(book.bookId)) {
            seenIds.add(book.bookId)
            uniqueBooks.push(book)
          }
        })
        historyList.value = uniqueBooks
        
        console.log('处理后的浏览历史:', historyList.value)
        
        if (historyList.value.length === 0) {
          uni.showToast({
            title: '暂无浏览历史',
            icon: 'none'
          })
        }
      } else {
        throw new Error(res.data.message || '获取数据失败')
      }
    } else {
      throw new Error(`HTTP ${res.statusCode}`)
    }
  } catch (error) {
    console.error('获取浏览历史失败:', error)
    uni.showToast({
      title: '获取浏览历史失败: ' + (error.message || '未知错误'),
      icon: 'none'
    })
  } finally {
    loading.value = false
  }
}

// 清空历史记录
const clearHistory = async () => {
  const user = uni.getStorageSync('userInfo')
  if (!user?.U_Id) return
  
  uni.showModal({
    title: '提示',
    content: '确定要清空所有浏览历史吗？',
    success: async (res) => {
      if (res.confirm) {
        try {
          const [err, result] = await new Promise((resolve) => {
            uni.request({
              url: `${BASE_URL}/api/history/clear`,
              method: 'DELETE',
              data: { userId: user.U_Id },
              header: {
                'Content-Type': 'application/x-www-form-urlencoded'
              },
              success: (res) => resolve([null, res]),
              fail: (err) => resolve([err, null])
            })
          })
          
          if (err) throw err
          
          if (result.statusCode === 200 && result.data.code === 200) {
            historyList.value = []
            uni.showToast({
              title: '已清空浏览历史',
              icon: 'success'
            })
          } else {
            throw new Error(result.data?.message || '清空失败')
          }
        } catch (error) {
          console.error('清空浏览历史失败:', error)
          uni.showToast({
            title: '清空浏览历史失败: ' + (error.message || '未知错误'),
            icon: 'none'
          })
        }
      }
    }
  })
}

// 跳转到书籍详情
const goToDetail = (bookId) => {
  if (!bookId) {
    uni.showToast({
      title: '书籍ID无效',
      icon: 'none'
    })
    return
  }
  
  uni.navigateTo({
    url: `/pages/bookdetail/bookdetail?id=${bookId}`
  })
}

// 格式化时间显示
const formatTime = (timeStr) => {
  if (!timeStr) return '未知时间'
  try {
    const date = new Date(timeStr)
    if (isNaN(date.getTime())) return '未知时间'
    
    return `${date.getFullYear()}-${padZero(date.getMonth()+1)}-${padZero(date.getDate())} ${padZero(date.getHours())}:${padZero(date.getMinutes())}`
  } catch (error) {
    console.error('时间格式化错误:', error)
    return '未知时间'
  }
}

// 补零函数
const padZero = (num) => {
  return num < 10 ? `0${num}` : num
}

// 页面挂载时加载数据
onMounted(() => {
  console.log('浏览历史页面已挂载')
})
</script>

<style lang="scss">
.history-container {
  padding: 20rpx;
  height: 100vh;
  background-color: #f5f5f5;
}

.history-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 30rpx;
  background-color: #fff;
  border-radius: 16rpx;
  margin-bottom: 20rpx;
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.05);

  .title {
    font-size: 36rpx;
    font-weight: bold;
    color: #333;
  }

  .clear-btn {
    font-size: 28rpx;
    color: #f56c6c;
    padding: 10rpx 20rpx;
    border-radius: 8rpx;
    
    &:active {
      background-color: #f0f0f0;
    }
  }
}

.history-list {
  height: calc(100vh - 180rpx);
  background-color: #fff;
  border-radius: 16rpx;
  padding: 0 20rpx;
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.05);
}

.history-item {
  display: flex;
  align-items: center;
  padding: 25rpx 0;
  border-bottom: 1rpx solid #f0f0f0;
  transition: background-color 0.2s;

  &:last-child {
    border-bottom: none;
  }

  &:active {
    background-color: #f8f8f8;
  }

  .book-cover {
    width: 120rpx;
    height: 160rpx;
    border-radius: 8rpx;
    margin-right: 20rpx;
    background-color: #f0f0f0;
    flex-shrink: 0;
  }

  .book-info {
    flex: 1;
    display: flex;
    flex-direction: column;
    justify-content: space-between;
    height: 160rpx;
    overflow: hidden;

    .book-name {
      font-size: 32rpx;
      font-weight: bold;
      color: #333;
      display: -webkit-box;
      -webkit-box-orient: vertical;
      -webkit-line-clamp: 2;
      overflow: hidden;
      line-height: 1.4;
      margin-bottom: 8rpx;
    }

    .book-author {
      font-size: 26rpx;
      color: #666;
      margin-bottom: 6rpx;
    }

    .book-score {
      font-size: 24rpx;
      color: #ff6b35;
      font-weight: 500;
      margin-bottom: 6rpx;
    }

    .book-types {
      display: flex;
      flex-wrap: wrap;
      margin: 8rpx 0;
      
      .type-tag {
        font-size: 22rpx;
        color: #3a7afe;
        background-color: #ecf5ff;
        padding: 4rpx 12rpx;
        border-radius: 20rpx;
        margin-right: 10rpx;
        margin-bottom: 6rpx;
        border: 1rpx solid #d4edff;
      }
    }

    .book-publisher {
      font-size: 24rpx;
      color: #888;
      margin-bottom: 6rpx;
    }

    .view-time {
      font-size: 24rpx;
      color: #999;
      margin-top: auto;
    }
  }

  uni-icons {
    margin-left: 20rpx;
    flex-shrink: 0;
  }
}

.empty-tip {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 100rpx 0;

  image {
    width: 200rpx;
    height: 200rpx;
    margin-bottom: 30rpx;
    opacity: 0.6;
  }

  text {
    font-size: 28rpx;
    color: #999;
  }
}

.loading-tip {
  padding: 40rpx 0;
  display: flex;
  justify-content: center;
  align-items: center;
  color: #999;
  font-size: 28rpx;

  &::before {
    content: '';
    width: 30rpx;
    height: 30rpx;
    border: 3rpx solid #e0e0e0;
    border-top-color: #999;
    border-radius: 50%;
    animation: spin 1s linear infinite;
    margin-right: 20rpx;
  }
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

/* 响应式设计 */
@media screen and (max-width: 750rpx) {
  .history-item {
    .book-cover {
      width: 100rpx;
      height: 130rpx;
    }
    
    .book-info {
      height: 130rpx;
      
      .book-name {
        font-size: 30rpx;
      }
      
      .book-author {
        font-size: 24rpx;
      }
    }
  }
}
</style>